package com.jiuzhi.app.common.wxutil;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class WXPayOrderUtil {

    public static Map<String, String> sendHttpRequestWechat(String xmlReq, String remoteUrl) {
		URL url = null;
		Map<String, String> retMap = new HashMap<String, String>();
		HttpURLConnection httpurlconnection = null;
		try {
			// 1.创建URL实例
			url = new URL(remoteUrl);
			// 2.创建连接
			httpurlconnection = (HttpURLConnection) url.openConnection();
			// 3.设置允许使用输出流写内容
			httpurlconnection.setDoOutput(true);
			// 4.设置请求方式为POST
			httpurlconnection.setRequestMethod("POST");
			// 5.设置头信息，标识该内容为XML
			httpurlconnection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
			// 6.设置头部关于浏览器的版本
			httpurlconnection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:53.0) Gecko/20100101 Firefox/53.0");
			// 7.获取输出流
			OutputStream os = httpurlconnection.getOutputStream();
			// 8.向流中写入数据
			os.write(xmlReq.getBytes("UTF-8"));
			// 9.清空并关闭输出流
			os.flush();
			os.close();
			// 10.获取返回流并解析
			InputStream responseInputStream = httpurlconnection.getInputStream();
			SAXBuilder sax = new SAXBuilder();
			Document doc = sax.build(responseInputStream);
			Element root = doc.getRootElement();
			if (null != root) {
				Iterator it = root.getChildren().iterator();
				while (it.hasNext()) {
					Element elm = (Element) it.next();
					retMap.put(elm.getName(), elm.getTextTrim());
				}

			}
		} catch (Exception e) {
		} finally {
			if (httpurlconnection != null) {
				httpurlconnection.disconnect();
			}
		}
		return retMap;
	}
}
